<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索与添加 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入用户名" clearable @clear="getUserList" v-model="queryInfo.query">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="adddialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="userList" style="width: 100%" border>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
        <el-table-column label="状态" width="180">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" @click="removeUserById(scope.row.id)"></el-button>
            <!-- 分配角色按钮 + 鼠标提示文字 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="adddialogVisible" width="50%" @close="addDialogClosed">
      <!-- 内容主体 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog title="修改" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 内容区 -->
      <el-form :model="editForm" rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="emali">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
 
<script>
export default {
  name: 'Users',
  data() {
    // 验证邮箱的自定义规则
    var checkEmail = (rule, value, cb) => {
      const checkEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
      if (checkEmail.test(value)) return cb()

      cb(new Error('邮箱不合法！'))
    }
    // 验证手机号的自定义规则
    let checkMobile = (rule, value, cb) => {
      const checkMobile = /^[1][3,4,5,7,8][0-9]{9}$/
      if (checkMobile.test(value)) return cb()

      cb(new Error('手机号不合法！'))
    }
    return {
      // 获取用户列表的参数
      queryInfo: {
        query: '',  // 查询参数 -- 搜索关键字
        pagenum: 1,  // 页码
        pagesize: 2,  // 显示条数
      },
      userList: [],  // 用户列表
      total: 0,  // 数据条数
      adddialogVisible: false, // 控制添加用户对话框的显示状态
      addForm: {  // 添加用户的表单数据
        username: '',  // 用户名
        password: '',  // 密码
        email: '',  // 邮箱
        mobile: '',  // 手机号
      },
      addFormRules: {  // 添加用户的表单验证规则
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editDialogVisible: false,  // 控制修改用户信息对话框的显示状态
      editForm: {},  // 查询到的用户信息
      editFormRules: {  // 修改用户信息的表单验证规则
        email: [
          { required: true, message: '请输入邮箱！', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号！', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
      },
    }
  },
  created() {
    this.getUserList();  // 获取用户列表
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('/users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('用户信息列表获取失败！')
      this.userList = res.data.users;
      this.total = res.data.total;
      console.log(res);
    },
    // 监听分页改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听 switch开关 组件改变
    async userStateChanged(userInfo) {
      console.log('123+' + userInfo);
      const { data: res } = await this.$http.put(`/users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('用户状态更新成功！')
    },
    // 监听 增加用户对话框 关闭 - 重置表单
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击 对话框的确定按钮 添加用户 - 预校验
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return

        // 发起添加用户的请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败！')
        this.$message.success('添加用户成功！')
        //隐藏会话
        this.adddialogVisible = false

        // 刷新列表
        this.getUserList();
      })
    },
    // 修改用户对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('users/' + id)
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error('查询用户信息失败！')

      this.editForm = res.data

      this.editDialogVisible = true
    },
    // 监听 修改用户对话框 关闭 - 重置表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 点击 对话框的确定按钮 修改用户 - 预校验
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return

        // 发起修改用户请求
        const { data: res } = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
        if (res.meta.status !== 200) return this.$message.error('修改用户信息失败！')

        this.editDialogVisible = false

        this.getUserList();

        this.$message.success('修改用户信息成功！')

      })
    },
    // 删除用户信息
    async removeUserById(id) {
      // 弹框 - 点击确认返回confirm字符串 ；点击取消使用catch返回cancel字符串
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除！')

      const {data:res} = await this.$http.delete('users/' + id)
      if(res.meta.status !== 200) return this.$message.error('删除用户失败！')

      this.$message.success('删除用户成功！')

      this.getUserList()
    },
  },
}
</script>
 
<style lang='less' scoped>
.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, .15) !important;
}
</style>